import asyncio
import httpx
import json
import requests

# 发送GET请求
def get_access_token():
    AppID = "wxca30233f9bf3683e"
    AppSecret = "2894f0307d447136efabc3d5eb0caba2"
    # 微信API的URL
    url = "https://api.weixin.qq.com/cgi-bin/token"

    # 请求参数
    params = {
        "grant_type": "client_credential",
        "appid": AppID,  # 替换为你的appid
        "secret": AppSecret  # 替换为你的appsecret
    }
    response = requests.get(url, params=params)
    print(response.text)
    access_token = json.loads(response.text)["access_token"]
    return access_token


# 发送POST请求的函数
async def send_wechat_message(access_token, message_data):
    # 微信API发送消息的URL
    url = "https://api.weixin.qq.com/cgi-bin/message/custom/send"

    # 你已经获取到的access_token
    access_token = access_token.get("access_token")
    print(access_token)
    # 要发送的消息内容

    # 将access_token拼接到URL中
    url_with_token = f"{url}?access_token={access_token}"

    # 发送POST请求
    async with httpx.AsyncClient() as client:
        response = await client.post(url_with_token, json=message_data)
    print(response.text)
    # 返回响应
    return response.json()

async def main(content):
    access_token = await get_access_token()
    message_data = {
        "touser": "oEjvD0nAVy0q83EWz2lDHemaNzwc",
        "msgtype": "text",
        "text": {
            "content": "Hello World"
        }
    }
    await send_wechat_message(access_token, message_data)

if __name__ == '__main__':
    asyncio.run(main("Hello World"))
